#include "FriendListView.h"

FriendListView::FriendListView(QWidget* parent):QListView(parent) {}

void FriendListView::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton||event->button()==Qt::RightButton){
        QModelIndex index = indexAt(event->pos());// 获取点击位置的索引
        if(index.isValid()){
            setCurrentIndex(index);
            clicked(index);// 模拟点击动作
        }
    }

    QListView::mousePressEvent(event);
}

FriendItemDelegate::FriendItemDelegate(QWidget *parent):QStyledItemDelegate(parent){}

QSize FriendItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    return QSize(190,50);// 设置大小为190×50
}

void FriendItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 1.检查是否有效
    if (!index.isValid()){
        return;
    }
    painter->save();// 保存当前绘制状态
    painter->setRenderHint(QPainter::Antialiasing); // 反锯齿
    painter->setRenderHint(QPainter::TextAntialiasing); // 文本反锯齿

    // 2.绘制每一项的背景颜色（鼠标悬停反应）
    QColor backgroundColor;
    if(option.state & QStyle::State_Selected){
        backgroundColor = QColor(100, 150, 200); // 选中是深蓝色
    }
    else if(option.state & QStyle::State_MouseOver){
        backgroundColor = QColor(173,216,230);// 鼠标悬浮是蔚蓝色
    }
    else {
        backgroundColor = option.palette.window().color();// 否则是默认的颜色
    }
    painter->setBrush(backgroundColor);// 设置颜色
    painter->setPen(Qt::NoPen);// 不带边框
    painter->drawRect(option.rect);// 绘制背景


    // 3.绘制左边的头像或图标
    QPixmap pixmap = index.data(Qt::UserRole + 1).value<QPixmap>();
    painter->drawPixmap(option.rect.x() + 5,option.rect.y() + 5,40,40, pixmap.scaled(40,40,Qt::KeepAspectRatioByExpanding,Qt::SmoothTransformation));


    // 4.绘制中间的文本
    QColor textColor = QColor::fromString("#87CEEB");
    QFont font = painter->font();//默认字体
    font.setPointSize(10);//设置字号
    painter->setFont(font);
    painter->setPen(textColor);
    QString text = index.data(Qt::UserRole + 2).toString();
    painter->drawText(option.rect.x() + 50,option.rect.y() + 10,100,30, Qt::AlignVCenter, text);


    // 5.绘制最右边的未读提示圆点（如果有的话,只有好友申请项需要）
    if(index.row() == 0 && index.data(Qt::UserRole + 3).value<bool>() == true){
        painter->setBrush(Qt::red);// 未读消息显示成红色
        painter->drawEllipse(option.rect.x() + 155,option.rect.y() + 15,20,20);
    }

    painter->restore();// 恢复绘制状态
}
